package com.example.dao;

import com.example.model.Answer;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class AnswerDAO {
    private DataSource dataSource;

    public AnswerDAO() throws NamingException, SQLException {
        Context context = new InitialContext();
        dataSource = (DataSource) context.lookup("java:comp/env/jdbc/dev_community");
    }

    public List<Answer> getAnswersByQuestionId(int questionId) throws SQLException {
        List<Answer> answers = new ArrayList<>();
        String query = "SELECT a.*, u.username AS author FROM answers a LEFT JOIN users u ON a.user_id = u.id WHERE a.question_id = ? ORDER BY a.created_at ASC";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setInt(1, questionId);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                Answer answer = new Answer();
                answer.setId(rs.getInt("id"));
                answer.setQuestionId(rs.getInt("question_id"));
                answer.setUserId(rs.getInt("user_id"));
                answer.setContent(rs.getString("content"));
                answer.setAuthor(rs.getString("author"));
                answer.setCreatedAt(rs.getTimestamp("created_at"));
                answers.add(answer);
            }
        }
        return answers;
    }

    public void addAnswer(Answer answer) throws SQLException {
        String query = "INSERT INTO answers (question_id, user_id, content) VALUES (?, ?, ?)";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setInt(1, answer.getQuestionId());
            stmt.setInt(2, answer.getUserId());
            stmt.setString(3, answer.getContent());
            stmt.executeUpdate();
        }
    }
}